package com.alkandros.myloke.activities;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.alkandros.myloke.R;
import com.alkandros.myloke.activities.BaseActivity.LocationCallBack;
import com.alkandros.myloke.managers.ApiManager;
import com.alkandros.myloke.managers.NotifyManager;
import com.alkandros.myloke.managers.POSTApiManager;
import com.alkandros.myloke.managers.ApiManager.ApiResponseListner;
import com.alkandros.myloke.managers.AppPreferenceManager;
import com.alkandros.myloke.managers.POSTApiManager.DataDownloadListener;
import com.alkandros.myloke.models.FaithModel;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.VisibleRegion;
import com.google.gson.JsonObject;

/**
 * @author Jiju Induchoodan
 * 
 */
public class MainActivity extends BaseActivity implements OnClickListener,LocationCallBack {

	private Button buttonSubmit;
	private Spinner spinnerFaith;
	private EditText editTextName;
	private EditText editTextNumber;
	private ArrayList<FaithModel> faithModelArray;
	private POSTApiManager postApiManager;
//	private GoogleMap mMap;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Bundle extras = getIntent().getExtras();
		if(extras != null)
		{
			faithModelArray = (ArrayList<FaithModel>) extras.get("faithArray");
		}
		
		
		buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
		spinnerFaith = (Spinner)findViewById(R.id.spinnerFaith);
		editTextName = (EditText)findViewById(R.id.editTextName);
		editTextNumber = (EditText)findViewById(R.id.editTextNumber);
		buttonSubmit.setOnClickListener(this);
		
		/*ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.faith_arrays));
			dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinnerFaith.setAdapter(dataAdapter);*/
		
		String[] faithArray = new String[faithModelArray.size()];
		for (int i = 0; i < faithModelArray.size(); i++) {
			faithArray[i] = faithModelArray.get(i).getFaith();
	    }
	//	faithArray = faithModelArray.toArray(faithArray);
		
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, faithArray);
			dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinnerFaith.setAdapter(dataAdapter);
	}
	/**
	 * Button to get current Location. This demonstrates how to get the current
	 * Location as required without needing to register a LocationListener.
	 */
	public void showMyLocation(View view) {
		if (mLocationClient != null && mLocationClient.isConnected()) {
			String msg = "Location = " + mLocationClient.getLastLocation();
		}
	}
	private class OverscrollHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			CameraPosition position = mMap.getCameraPosition();
			VisibleRegion region = mMap.getProjection().getVisibleRegion();
			float zoom = 0;
			if (position.zoom < MIN_ZOOM)
				zoom = MIN_ZOOM;
			if (position.zoom > MAX_ZOOM)
				zoom = MAX_ZOOM;
			LatLng correction = getLatLngCorrection(region.latLngBounds);
			if (zoom != 0 || correction.latitude != 0
					|| correction.longitude != 0) {
				zoom = (zoom == 0) ? position.zoom : zoom;
				double lat = position.target.latitude + correction.latitude;
				double lon = position.target.longitude + correction.longitude;
				CameraPosition newPosition = new CameraPosition(new LatLng(lat,
						lon), zoom, position.tilt, position.bearing);
				CameraUpdate update = CameraUpdateFactory
						.newCameraPosition(newPosition);
				mMap.moveCamera(update);
			}
			/* Recursively call handler every 100ms */
			sendEmptyMessageDelayed(0, 100000);
		}
	}
	private LatLng getLatLngCorrection(LatLngBounds cameraBounds) {
		double latitude = 0, longitude = 0;
		if (cameraBounds.southwest.latitude < BOUNDS.southwest.latitude) {
			latitude = BOUNDS.southwest.latitude
					- cameraBounds.southwest.latitude;
		}
		if (cameraBounds.southwest.longitude < BOUNDS.southwest.longitude) {
			longitude = BOUNDS.southwest.longitude
					- cameraBounds.southwest.longitude;
		}
		if (cameraBounds.northeast.latitude > BOUNDS.northeast.latitude) {
			latitude = BOUNDS.northeast.latitude
					- cameraBounds.northeast.latitude;
		}
		if (cameraBounds.northeast.longitude > BOUNDS.northeast.longitude) {
			longitude = BOUNDS.northeast.longitude
					- cameraBounds.northeast.longitude;
		}
		return new LatLng(latitude, longitude);
	}
	@Override
	public void onClick(View v) 
	{
		if (v == buttonSubmit) 
		{
			if(editTextName.getText().toString().equals("")||editTextNumber.getText().toString().equals(""))
			{
				Toast.makeText(MainActivity.this, "Please enter the values", Toast.LENGTH_LONG).show();
			}
			else
			{
				AppPreferenceManager.saveFaith(spinnerFaith.getSelectedItem().toString(), this);
				AppPreferenceManager.saveUserName(editTextName.getText().toString(), this);
				AppPreferenceManager.saveUserNumber(editTextNumber.getText().toString(), this);
				/*Intent intent = new Intent(MainActivity.this,NearbyActivity.class);
				startActivity(intent);
				finish();*/
				signupCall();
			
			}
			}
	}
	@Override
	public void locationObjectReceived(Location location) {
		
	}
	
	void signupCall()
	{
		postApiManager = new POSTApiManager(SINGUP_API, new String[] {"username","number","faith_type"},
				new String[] {editTextName.getText().toString(),editTextNumber.getText().toString(),
				spinnerFaith.getSelectedItem().toString()}, this);
		postApiManager.setDataDownloadListener(new DataDownloadListener() {
			@Override
			public void dataDownloadedSuccessfully(String response) {
						JSONObject js;
						try {
							js = new JSONObject(response);
							if(js.optString("status").equalsIgnoreCase("success"))
							{
								Intent intent = new Intent(MainActivity.this,NearbyActivity.class);
								startActivity(intent);
								finish();
							}
							else
							{
								NotifyManager.showShortToast(MainActivity.this, getString(R.string.common_error_message));
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							NotifyManager.showShortToast(MainActivity.this, getString(R.string.common_error_message));
						}
						
			}
		});
		postApiManager.execute();
	}
}